let time: number = (new Date()).getTime();

//默认过期时间72小时
const expire: number = time + 60 * 60 * 72 * 1000

interface res {
    data: any,
    exp: number
}
const useStorage = {
    /**
     * 写入缓存
     * @param key
     * @param value
     * @param session
     */
    setItem: (key: string, value: any, session?: boolean) => {
        let driver: any = session ? sessionStorage : localStorage
        let data: res = { data: value, exp: expire }
        driver.setItem(key, JSON.stringify(data))
    },
    /**
     * 读取缓存 自动判断过期时间
     * 过期则返回 undefined
     * @param key
     * @param session
     * @returns
     */
    getItem: (key: string, session?: boolean) => {
        let driver: any = session ? sessionStorage : localStorage
        let item: string = driver.getItem(key)
        if (item) {
            let result: res = JSON.parse(item)
            if (result.exp < time) {
                driver.setItem(key, '')
                return undefined
            } else {
                return result.data
            }
        } else {
            return undefined
        }
    },
    /**
     * 移除
     * @param key
     * @param session
     */
    removeItem: (key: string, session?: boolean) => {
        let driver: any = session ? sessionStorage : localStorage
        driver.removeItem(key)
    },
    /**
     * 清空缓存
     * @param session
     */
    clear: (session?: boolean) => {
        let driver: any = session ? sessionStorage : localStorage
        driver.clear()
    }
}
export default useStorage;